# -*- coding;utf-8 -*-
"""
File name : Pdf2OtherMiner.PY
Program IDE : PyCharm
Create file time: 2025/5/26 11:56
File Create By Author : 朱清闯
"""
import requests
import time


def mineru(file_url='', is_ocr=True, enable_formula=True, extra_formats=['docx','html','latex']):
    url = 'https://mineru.net/api/v4/extract/task'
    header = {
        'Content-Type': 'application/json',
        "Authorization": "Bearer eyJ0eXBlIjoiSldUIiwiYWxnIjoiSFM1MTIifQ.eyJqdGkiOiIxMTkwMzUiLCJyb2wiOiJST0xFX1JFR0lTVEVSIiwiaXNzIjoiT3BlblhMYWIiLCJpYXQiOjE3NDgyMzE2MjcsImNsaWVudElkIjoibGt6ZHg1N252eTIyamtwcTl4MnciLCJwaG9uZSI6IiIsIm9wZW5JZCI6bnVsbCwidXVpZCI6IjhjNzc4MTZkLTZmY2MtNDZhZS1iYzVkLTYyZTg3NDE2YmFkNSIsImVtYWlsIjoiIiwiZXhwIjoxNzQ5NDQxMjI3fQ.meQO8Mc847dTv8A2_FIndSKXmCsKBCQszfx1zuWoab1xiGWC3dpSs8v7YeAF2DOYY_ohMQVmjzJn0qJFFFrVZA"
    }

    data = {
        'url': file_url,
        'is_ocr': is_ocr,
        'enable_formula': enable_formula,
        'extra_formats': extra_formats,
    }

    res = requests.post(url, headers=header, json=data)
    print(res.status_code)
    print(res.json())
    task_id = ''
    status = res.json()['code']
    if status == 0:
        print("get task_id success!")
        task_id = res.json()["data"]['task_id']
    else:
        print(status)
        return False, res['msg']

    url = f'https://mineru.net/api/v4/extract/task/{task_id}'
    # res = requests.get(url, headers=header)
    # print(res.status_code)
    # print(res.json())
    # print(res.json()["data"])
    file_url = ''
    for i in range(30):
        res = requests.get(url, headers=header)
        status = res.status_code
        if status != 200:
            print("minerU return fail!")
            return False, 'minerU return fail!'
        result = res.json()["data"]
        state = result['state']
        if state == 'done':
            file_url = result['full_zip_url']
            break
        elif state in ['pending', 'running', 'converting']:
            time.sleep(1)
            continue
        elif state == 'failed':
            return False, ''

    if file_url == '':
        return False, ''
    return True, file_url
